package com.cjq.core.filter.impl;

import com.cjq.core.filter.GatewayFilter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.springframework.stereotype.Component;

@Component
public class RateLimitFilter implements GatewayFilter {
    private final RateLimiter limiter;

    public RateLimitFilter() {
        this(100);
    }

    public RateLimitFilter(int permitsPerSecond) {
        this.limiter = RateLimiter.create(permitsPerSecond);
    }

    @Override
    public FullHttpResponse postFilter(FullHttpRequest request, FullHttpResponse response) {
        return response;
    }

    @Override
    public boolean filter(FullHttpRequest request, ChannelHandlerContext ctx) {
        if (!limiter.tryAcquire()) {
            sendError(ctx, HttpResponseStatus.TOO_MANY_REQUESTS);
            return false;
        }
        return true;
    }

    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus tooManyRequests) {
    }
}